package com.awenhui.demo.core.utils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日志记录帮助类
 *
 * @author yuxf
 * @version 1.0
 * @date 2020/7/22 9:35
 */
public class LogUtils {

    public static String LOG_ROOT = "D:\\ktwl\\赛岭公寓\\赛领公寓\\icbc\\pay\\order.txt";

    /**
     * @param content
     * @param path
     * @throws IOException
     */
    public static synchronized void writeLog(String content, String path) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        File file = new File(path);
        //如果传入的是目录则自动生成一个当天日期命名的txt日志文件
        //不用file.isFile()是因为linux下一切皆文件，目录也会被当做文件
        if (!path.contains(".")) {
            file = new File(path+File.separator+sdf.format(date) + ".txt");
        }
        System.out.println(file.getAbsolutePath());
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        if (!file.exists()) file.createNewFile();
        //追加写入文本
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(file, true)));
        out.write("[" + sdfTime.format(date) + "]" + content);
        out.write("\r\n");
        out.close();
    }

}
